Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
# TODO: Make all necessary imports.
import warnings
warnings.filterwarnings('ignore')
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
import json
import time
from os import listdir
INFO:tensorflow:Enabling eager execution INFO:tensorflow:Enabling v2 tensorshape INFO:tensorflow:Enabling resource variables INFO:tensorflow:Enabling tensor equality INFO:tensorflow:Enabling control flow v2
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# TODO: Load the dataset with TensorFlow Datasets.
dataset , dataset_info = tfds.load('oxford_flowers102', with_info=True, as_supervised=True)
# TODO: Create a training set, a validation set and a test set.
train_set = dataset['train']
validation_set = dataset['validation']
test_set = dataset['test']
# TODO: Get the number of examples in each set from the dataset info.
n_train = dataset_info.splits['train'].num_examples
n_validation = dataset_info.splits['validation'].num_examples
n_test = dataset_info.splits['test'].num_examples
print(f"number of images in the train_set = {n_train}")
print(f"number of images in the validation_set = {n_validation}")
print(f"number of images in the test_set = {n_test}")
# TODO: Get the number of classes in the dataset from the dataset info.
n_classes = dataset_info.features['label'].num_classes
print(f"number of classes = {n_classes}")
number of images in the train_set = 1020 number of images in the validation_set = 1020 number of images in the test_set = 6149 number of classes = 102
# TODO: Print the shape and corresponding label of 3 images in the training set.
n = 1
for image , label in train_set.take(3) :
print (f'image {n} have a label of {label} and a shape of {image.shape}')
n +=1
image 1 have a label of 72 and a shape of (500, 667, 3) image 2 have a label of 84 and a shape of (500, 666, 3) image 3 have a label of 70 and a shape of (670, 500, 3)
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding image label.
for image , label in train_set.take(1) :
image = image.numpy()
label = label.numpy()
plt.imshow(image)
plt.title(label)
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
with open('label_map.json', 'r') as f:
class_names = json.load(f)
class_names_dict = dict()
for i in class_names:
class_names_dict[str(int(i)-1)] = class_names[i]
print(class_names_dict)
{'20': 'fire lily', '2': 'canterbury bells', '44': 'bolero deep blue', '0': 'pink primrose', '33': 'mexican aster', '26': 'prince of wales feathers', '6': 'moon orchid', '15': 'globe-flower', '24': 'grape hyacinth', '25': 'corn poppy', '78': 'toad lily', '38': 'siam tulip', '23': 'red ginger', '66': 'spring crocus', '34': 'alpine sea holly', '31': 'garden phlox', '9': 'globe thistle', '5': 'tiger lily', '92': 'ball moss', '32': 'love in the mist', '8': 'monkshood', '101': 'blackberry lily', '13': 'spear thistle', '18': 'balloon flower', '99': 'blanket flower', '12': 'king protea', '48': 'oxeye daisy', '14': 'yellow iris', '60': 'cautleya spicata', '30': 'carnation', '63': 'silverbush', '67': 'bearded iris', '62': 'black-eyed susan', '68': 'windflower', '61': 'japanese anemone', '19': 'giant white arum lily', '37': 'great masterwort', '3': 'sweet pea', '85': 'tree mallow', '100': 'trumpet creeper', '41': 'daffodil', '21': 'pincushion flower', '1': 'hard-leaved pocket orchid', '53': 'sunflower', '65': 'osteospermum', '69': 'tree poppy', '84': 'desert-rose', '98': 'bromelia', '86': 'magnolia', '4': 'english marigold', '91': 'bee balm', '27': 'stemless gentian', '96': 'mallow', '56': 'gaura', '39': 'lenten rose', '46': 'marigold', '58': 'orange dahlia', '47': 'buttercup', '54': 'pelargonium', '35': 'ruby-lipped cattleya', '90': 'hippeastrum', '28': 'artichoke', '70': 'gazania', '89': 'canna lily', '17': 'peruvian lily', '97': 'mexican petunia', '7': 'bird of paradise', '29': 'sweet william', '16': 'purple coneflower', '51': 'wild pansy', '83': 'columbine', '11': "colt's foot", '10': 'snapdragon', '95': 'camellia', '22': 'fritillary', '49': 'common dandelion', '43': 'poinsettia', '52': 'primula', '71': 'azalea', '64': 'californian poppy', '79': 'anthurium', '75': 'morning glory', '36': 'cape flower', '55': 'bishop of llandaff', '59': 'pink-yellow dahlia', '81': 'clematis', '57': 'geranium', '74': 'thorn apple', '40': 'barbeton daisy', '94': 'bougainvillea', '42': 'sword lily', '82': 'hibiscus', '77': 'lotus lotus', '87': 'cyclamen', '93': 'foxglove', '80': 'frangipani', '73': 'rose', '88': 'watercress', '72': 'water lily', '45': 'wallflower', '76': 'passion flower', '50': 'petunia'}
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding class name.
for image , label in train_set.take(1) :
image = image.numpy()
label = label.numpy()
label = class_names['{}'.format(label)]
plt.imshow(image)
plt.title(label)
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>
# TODO: Create a pipeline for each set.
image_size = 224
def normalize_images (image , label) :
image = tf.cast(image ,tf.float32)
image = tf.image.resize(image, (image_size, image_size))
image /= 255
return image , label
num_training_examples = dataset_info.splits['train'].num_examples
batch_size = 64
train_batches = train_set.shuffle(n_train//4).map(normalize_images).batch(batch_size).prefetch(1)
validation_batches = validation_set.shuffle(n_validation//4).map(normalize_images).batch(batch_size).prefetch(1)
test_batches = test_set.shuffle(n_test//4).map(normalize_images).batch(batch_size).prefetch(1)
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# TODO: Build and train your network.
url = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
feature_extractor = hub.KerasLayer(
url,
input_shape=(image_size, image_size,3),
trainable = False
)
model = tf.keras.Sequential()
model.add(feature_extractor)
model.add(tf.keras.layers.Dense(512, activation='relu'))
model.add(tf.keras.layers.Dropout(0.1))
model.add(tf.keras.layers.Dense(256, activation='relu'))
model.add(tf.keras.layers.Dropout(0.1))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dropout(0.1))
model.add(tf.keras.layers.Dense(102, activation='softmax'))
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= keras_layer (KerasLayer) (None, 1280) 2257984 _________________________________________________________________ dense (Dense) (None, 512) 655872 _________________________________________________________________ dropout (Dropout) (None, 512) 0 _________________________________________________________________ dense_1 (Dense) (None, 256) 131328 _________________________________________________________________ dropout_1 (Dropout) (None, 256) 0 _________________________________________________________________ dense_2 (Dense) (None, 128) 32896 _________________________________________________________________ dropout_2 (Dropout) (None, 128) 0 _________________________________________________________________ dense_3 (Dense) (None, 102) 13158 ================================================================= Total params: 3,091,238 Trainable params: 833,254 Non-trainable params: 2,257,984 _________________________________________________________________
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
EPOCHS = 100
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
history = model.fit(train_batches,
epochs=EPOCHS,
validation_data=validation_batches,
callbacks=[early_stopping])
Epoch 1/100 16/16 [==============================] - 30s 1s/step - loss: 4.6592 - accuracy: 0.0173 - val_loss: 4.2336 - val_accuracy: 0.1235 Epoch 2/100 16/16 [==============================] - 15s 940ms/step - loss: 3.9379 - accuracy: 0.1685 - val_loss: 3.3493 - val_accuracy: 0.2755 Epoch 3/100 16/16 [==============================] - 15s 958ms/step - loss: 2.8713 - accuracy: 0.3480 - val_loss: 2.3509 - val_accuracy: 0.4480 Epoch 4/100 16/16 [==============================] - 15s 968ms/step - loss: 1.8468 - accuracy: 0.5346 - val_loss: 1.7150 - val_accuracy: 0.5951 Epoch 5/100 16/16 [==============================] - 16s 990ms/step - loss: 1.1837 - accuracy: 0.6930 - val_loss: 1.4139 - val_accuracy: 0.6480 Epoch 6/100 16/16 [==============================] - 16s 1s/step - loss: 0.8436 - accuracy: 0.7920 - val_loss: 1.2472 - val_accuracy: 0.6922 Epoch 7/100 16/16 [==============================] - 16s 1s/step - loss: 0.5942 - accuracy: 0.8374 - val_loss: 1.1889 - val_accuracy: 0.6922 Epoch 8/100 16/16 [==============================] - 16s 991ms/step - loss: 0.4174 - accuracy: 0.8984 - val_loss: 1.0773 - val_accuracy: 0.7176 Epoch 9/100 16/16 [==============================] - 17s 1s/step - loss: 0.2962 - accuracy: 0.9233 - val_loss: 1.0929 - val_accuracy: 0.7206 Epoch 10/100 16/16 [==============================] - 16s 1s/step - loss: 0.2690 - accuracy: 0.9248 - val_loss: 1.0022 - val_accuracy: 0.7500 Epoch 11/100 16/16 [==============================] - 19s 1s/step - loss: 0.1791 - accuracy: 0.9662 - val_loss: 1.0238 - val_accuracy: 0.7500 Epoch 12/100 16/16 [==============================] - 17s 1s/step - loss: 0.1261 - accuracy: 0.9731 - val_loss: 0.9619 - val_accuracy: 0.7578 Epoch 13/100 16/16 [==============================] - 17s 1s/step - loss: 0.1093 - accuracy: 0.9830 - val_loss: 0.9655 - val_accuracy: 0.7627 Epoch 14/100 16/16 [==============================] - 17s 1s/step - loss: 0.0906 - accuracy: 0.9838 - val_loss: 0.9427 - val_accuracy: 0.7725 Epoch 15/100 16/16 [==============================] - 17s 1s/step - loss: 0.0716 - accuracy: 0.9883 - val_loss: 1.0325 - val_accuracy: 0.7559 Epoch 16/100 16/16 [==============================] - 17s 1s/step - loss: 0.0723 - accuracy: 0.9867 - val_loss: 0.9535 - val_accuracy: 0.7686 Epoch 17/100 16/16 [==============================] - 17s 1s/step - loss: 0.0681 - accuracy: 0.9854 - val_loss: 0.9949 - val_accuracy: 0.7627 Epoch 18/100 16/16 [==============================] - 17s 1s/step - loss: 0.0518 - accuracy: 0.9896 - val_loss: 0.9584 - val_accuracy: 0.7569 Epoch 19/100 16/16 [==============================] - 17s 1s/step - loss: 0.0314 - accuracy: 0.9963 - val_loss: 0.9535 - val_accuracy: 0.7637
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
training_loss = history.history['loss']
validation_accuracy = history.history['val_accuracy']
validation_loss = history.history['val_loss']
l = range(len(training_accuracy))
plt.figure(figsize=(16, 8))
plt.subplot(121)
plt.plot(l, training_accuracy, label='Training Accuracy')
plt.plot(l, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(122)
plt.plot(l, training_loss, label='Training Loss')
plt.plot(l, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# TODO: Print the loss and accuracy values achieved on the entire test set.
# i wrote the code below but it didn't output any thing I still didn't find why
# result = model.evaluate(test_batches)
# print(f'(loss, accuracy) = {result}')
# but this peace of code solved the problem (https://keras.io/guides/training_with_built_in_methods/)
print("Evaluate")
result = model.evaluate(test_batches)
dict(zip(model.metrics_names, result))
Evaluate 97/97 [==============================] - 50s 499ms/step - loss: 1.1688 - accuracy: 0.7216
{'loss': 1.168818473815918, 'accuracy': 0.7215807437896729}
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# TODO: Save your trained model as a Keras model.
time_stamp = time.time()
saved_model_path = 'image_classifer' + str(time_stamp) + '.h5'
model.save(saved_model_path)
time_stamp
1619131907.0341396
Load the Keras model you saved above.
# TODO: Load the Keras model
the_loaded_model = tf.keras.models.load_model(saved_model_path,custom_objects={'KerasLayer':hub.KerasLayer})
the_loaded_model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= keras_layer (KerasLayer) (None, 1280) 2257984 _________________________________________________________________ dense (Dense) (None, 512) 655872 _________________________________________________________________ dropout (Dropout) (None, 512) 0 _________________________________________________________________ dense_1 (Dense) (None, 256) 131328 _________________________________________________________________ dropout_1 (Dropout) (None, 256) 0 _________________________________________________________________ dense_2 (Dense) (None, 128) 32896 _________________________________________________________________ dropout_2 (Dropout) (None, 128) 0 _________________________________________________________________ dense_3 (Dense) (None, 102) 13158 ================================================================= Total params: 3,091,238 Trainable params: 833,254 Non-trainable params: 2,257,984 _________________________________________________________________
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def process_image(image) :
image = tf.convert_to_tensor(image)
image = tf.image.resize(image , (224,224))
image /= 225
image = image.numpy()
return image
To check your process_image function we have provided 4 images in the ./test_images/ folder:
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
from PIL import Image
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)
processed_test_image = process_image(test_image)
fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
WARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
# TODO: Create the predict function
def predict(image_path, model, top_k):
image = Image.open(image_path)
test_image = np.asarray(image)
test_image = process_image(test_image)
print(test_image.shape, np.expand_dims(test_image,axis=0).shape)
prob_pred = model.predict(np.expand_dims(test_image,axis=0))
prob_pred = prob_pred[0].tolist()
#TODO: make these changes in the command line code as well
values, indices= tf.math.top_k(prob_pred, k=top_k)
probs=values.numpy().tolist()
classes=indices.numpy().tolist()
return probs, classes
probs, classes = predict('./test_images/wild_pansy.jpg',the_loaded_model, 5)
(224, 224, 3) (1, 224, 224, 3)
pred_label_names = [class_names_dict[str(i)] for i in classes]
print("prediction probabilities :\n",probs)
print('prediction classes:\n',classes)
print('prediction labels:\n',pred_label_names)
prediction probabilities : [0.9990801811218262, 0.00034672257606871426, 0.00033766485285013914, 0.00012807073653675616, 3.455521436990239e-05] prediction classes: [51, 33, 63, 68, 85] prediction labels: ['wild pansy', 'mexican aster', 'silverbush', 'windflower', 'tree mallow']
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.
# TODO: Plot the input image along with the top 5 classes
images_names = [f for f in listdir('./test_images')]
images_paths = ['./test_images/' + f for f in images_names]
n = 0
for image_path in images_paths :
image = Image.open(image_path)
image = np.asarray(image)
image = process_image(image)
probs, classes = predict(image_path, the_loaded_model, 5)
classes_names_list = []
for i in list(classes) :
classes_names_list.append(class_names[str(i +1)])
fig, (ax1, ax2) = plt.subplots(figsize=(12,5), ncols=2)
ax1.imshow(image)
ax1.set_title(images_names[n])
ax2.barh(classes_names_list, probs)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
n += 1
WARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
(224, 224, 3) (1, 224, 224, 3)
WARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
(224, 224, 3) (1, 224, 224, 3)
WARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
(224, 224, 3) (1, 224, 224, 3)
WARNING:matplotlib.image:Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
(224, 224, 3) (1, 224, 224, 3)